package imv3.foo.server.handler;

import imv3.protocol.request.JoinGroupRequestPacket;
import imv3.protocol.response.JoinGroupResponsePacket;
import imv3.util.SessionUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;

/**
 * @author @xsomnus666_xiawenye★
 * @since 2019/4/26 0026 10:40
 * 当你发现自己的才华撑不起野心时，就请安静下来学习吧
 */
@ChannelHandler.Sharable
public class JoinGroupRequestHandler extends SimpleChannelInboundHandler<JoinGroupRequestPacket> {

    public static final JoinGroupRequestHandler INSTANCE =  new JoinGroupRequestHandler();

    private JoinGroupRequestHandler() {

    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, JoinGroupRequestPacket joinGroupRequestPacket) throws Exception {

        ChannelGroup channelGroup = SessionUtil.getChannelGroup(joinGroupRequestPacket.getGroupId());
        JoinGroupResponsePacket joinGroupResponsePacket = new JoinGroupResponsePacket();
        joinGroupResponsePacket.setGroupId(joinGroupRequestPacket.getGroupId());
        if (channelGroup != null) {
            channelGroup.add(ctx.channel());
            joinGroupResponsePacket.setSuccess(true);
        } else {
            joinGroupResponsePacket.setSuccess(false);
            joinGroupResponsePacket.setReason("群聊[" + joinGroupRequestPacket.getGroupId() + "]不存在");
        }

        ctx.channel().writeAndFlush(joinGroupResponsePacket);

    }
}
